<template>
  <view class="dpc-center-center height-50vh">
    <view class="pa-4">
      <text style="font-size: 18px; color: #707070">{{
        userInfo && userInfo.mobile ? userInfo.mobile : '未绑定手机号码'
      }}</text>
    </view>
    <nut-button
      :disabled="!agree"
      :loading="bindLoading"
      type="primary"
      open-type="getPhoneNumber"
      style="width: 88%"
      @getphonenumber="getPhoneNumber"
      >{{ userInfo && userInfo.mobile ? '更改手机号' : '绑定手机号' }}
    </nut-button>
    <view class="mt-3 dpr-center-center" style="font-size: 14px">
      <nut-checkbox v-model="agree">
        <view>
          <text>我已阅读并同意</text>
        </view>
      </nut-checkbox>
      <view style="color: #fa2c19" @click="Taro.navigateTo({ url: '/pages/agreement/index?type=ua&title=用户协议' })"
        >《用户协议》</view
      >
      <text>和</text>
      <view style="color: #fa2c19" @click="Taro.navigateTo({ url: '/pages/agreement/index?type=pa&title=隐私协议' })"
        >《隐私协议》</view
      >
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro, { useLoad } from '@tarojs/taro';
import { ref } from 'vue';
import { bindMobileApi, getPersonalInfoApi, UserType } from '@/api/user';

const userInfo = ref<UserType>();
const getUserInfo = () => {
  getPersonalInfoApi({}).then((res) => {
    userInfo.value = res.result;
  });
};
const agree = ref(false);
const bindLoading = ref(false);
const getPhoneNumber = (e) => {
  console.log('绑定手机号:', e);
  if (!agree.value) {
    Taro.showToast({
      title: '请同意相关协议',
      icon: 'none',
    });
    return;
  }
  if (bindLoading.value === true) {
    return;
  }
  if (!e.detail.iv) {
    Taro.showToast({
      title: '获取手机号失败',
      icon: 'none',
    });
    return;
  }

  bindLoading.value = true;
  const invite = Taro.getStorageSync('invite_id');
  const loginData = {
    type: '',
    vi: '',
    code: '',
    mobileCode: '',
    encryptedData: '',
    rawData: '',
    signature: '',
    cloudID: '',
    invite_id: Number(invite),
    userInfo: {},
  };
  loginData.vi = e.detail.iv;
  loginData.encryptedData = e.detail.encryptedData;
  Taro.login({
    success: (ret) => {
      loginData.code = ret.code;
      bindMobileApi(loginData)
        .then((r) => {
          console.log('请求后台', r);
          if (r.success) {
            Taro.showToast({ title: '设置成功' });
          }
        })
        .finally(() => {
          bindLoading.value = false;
        });
    },
  });
};
useLoad(() => {
  getUserInfo();
});
</script>

<style lang="less" scoped></style>
